package com.ruoyi.mall.product.domain.exception;

import com.ruoyi.common.core.enums.BizCodeEnum;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @program: zqs-mall
 * @description: 商城模块统一异常处理
 * @author: Mr.Zhang
 * @create: 2022-06-01 17:25
 **/

@RestControllerAdvice(basePackages = "com.ruoyi.mall.product.interfaces.facade")
public class MallException {

    private static final Logger LOGGER = LoggerFactory.getLogger(MallException.class);

    /**
     * 数据校验的异常
     * TODO 这里规定状态码为5位
     *  10: 通用的错误
     *    001: 参数格式校验
     *  11: 商品
     *  12: 订单
     *  13: 购物车
     *  14: 物流
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(error -> {
            map.put(error.getField(), error.getDefaultMessage());

        });

        LOGGER.error("数据校验出现异常", e.getMessage());
        return AjaxResult.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage(),map);
    }

    /**
     * 如果是其他异常
     * @param throwable 异常
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public AjaxResult handleValidException(Throwable throwable) {

        LOGGER.error("错误",throwable);
        return AjaxResult.error();
    }

}
